package com.example.service.impl;

import com.alibaba.excel.EasyExcel;
import com.example.mapper.CategoryMapper;
import com.example.pojo.Category;
import com.example.service.CategoryService;
import com.example.util.ThreadLocalUtil;
import com.example.vo.CategoryExcelVo;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> list() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        System.out.println(id);
        return categoryMapper.list(id);
    }

    @Override
    public void AddCategory(Category category) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        category.setCreateUser(id);
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.AddCategory(category);
    }

    @Override
    public void updateCategory(Category category) {
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.updateCategory(category);
    }

    @Override
    public Category GetCategoryById(Integer id) {
        Category category = categoryMapper.GetCategoryById(id);
        return category;
    }

    @Override
    public void deleteCategoryById(Integer id) {
        categoryMapper.deleteCategoryById(id);
    }

    @Override
    public void exportData(HttpServletResponse response) {
        System.out.println("调用成功");
        try {

            // 设置响应结果类型
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");

            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("分类数据", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");

            // 查询数据库中的数据
//            Map<String, Object> map = ThreadLocalUtil.get();
//            Integer id = (Integer) map.get("id");
            List<Category> categoryList = categoryMapper.selectExportData();
            for (Category category : categoryList) {
                System.out.println(category);
            }
            List<CategoryExcelVo> categoryExcelVoList = new ArrayList<>(categoryList.size());
//            ExcelUtil.exportExcel(categoryExcelVoList,"宿舍分类数据","宿舍分类", CategoryExcelVo.class,"宿舍分类数据记录表.xlsx",response);
            // 将从数据库中查询到的Category对象转换成CategoryExcelVo对象
            for (Category category : categoryList) {
                CategoryExcelVo categoryExcelVo = new CategoryExcelVo();
                BeanUtils.copyProperties(category, categoryExcelVo/*, CategoryExcelVo.class*/);
                System.out.println("----------categoryExcelVo"+categoryExcelVo);
                categoryExcelVoList.add(categoryExcelVo);
            }
            //测试，打印一下ExcelVo数据
            System.out.println("-----------------");
            for (CategoryExcelVo categoryExcelVo : categoryExcelVoList) {
                System.out.println(categoryExcelVo);
            }
            // 写出数据到浏览器端
            EasyExcel.write(response.getOutputStream(), CategoryExcelVo.class).sheet("分类数据").doWrite(categoryExcelVoList);


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // com.atguigu.spzx.service.impl#CategoryServiceImpl
    /*@Override
    public void importData(MultipartFile file) {
        try {
            //创建监听器对象，传递mapper对象
            ExcelListener<CategoryExcelVo> excelListener = new ExcelListener<>(categoryMapper);
            //调用read方法读取excel数据
            EasyExcel.read(file.getInputStream(),
                    CategoryExcelVo.class,
                    excelListener).sheet().doRead();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }*/


    @Override
    public List<Category> findAll() {
        List<Category> list = categoryMapper.findAll();
        return list;
    }

    @Override
    public String findCategoryName(Integer id) {
        Category category = new Category();
        category.setCategoryName(categoryMapper.findCategoryName(id));
        return category.getCategoryName();
    }


    @Override
    @SneakyThrows
    public void exportData1(HttpServletResponse response) {

//            // 设置响应结果类型
//            response.setContentType("application/vnd.ms-excel");
//            response.setCharacterEncoding("utf-8");
//
//            // 这里URLEncoder.encode可以防止中文乱码
//            String fileName = URLEncoder.encode("分类数据", "UTF-8");
//            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
//
//            // 获取日志记录器
//            Logger logger = LoggerFactory.getLogger(this.getClass());

            // 查询数据库中的数据
            Map<String, Object> map = ThreadLocalUtil.get();
            if (map == null || !map.containsKey("id")) {
                log.error("ThreadLocalUtil.get() 返回的 Map 为空或不包含 id 键");
            }

            Integer id = (Integer) map.get("id");
//            logger.debug("查询 id: {}", id);

            List<Category> categoryList = categoryMapper.selectAll(id);
            if (categoryList == null || categoryList.isEmpty()) {
                System.out.println("查询为空");
                log.error("查询结果为空");
            }
            System.out.println("查询不为空");
            List<CategoryExcelVo> categoryExcelVoList = new ArrayList<>(categoryList.size());

            // 将从数据库中查询到的 Category 对象转换成 CategoryExcelVo 对象
            for (Category category : categoryList) {
                CategoryExcelVo categoryExcelVo = new CategoryExcelVo();
                BeanUtils.copyProperties(category, categoryExcelVo);
                categoryExcelVoList.add(categoryExcelVo);
            }

            // 写出数据到浏览器端
            EasyExcel.write(response.getOutputStream(), CategoryExcelVo.class).sheet("分类数据").doWrite(categoryExcelVoList);
    }



}
